package com.cet.programmercarl.algorithmperformancanalysis.数组;

import java.util.HashMap;

/**
 * @program: algorithm
 * @description:
 * @author: 陈恩涛
 * @create: 2022-03-10 09:56
 **/
public class LC904 {
    public static void main(String[] args) {
        int[] a = {3, 3, 3, 1, 2, 1, 1, 2, 3, 3, 4};
        System.out.println(totalFruit(a));
    }

    public static int totalFruit(int[] tree) {
        int ans = 0, left = 0;
        Counter count = new Counter();
        for (int right = 0; right < tree.length; ++right) {
            count.add(tree[right], 1);
            while (count.size() >= 3) {
                count.add(tree[left], -1);
                if (count.get(tree[left]) == 0) {
                    count.remove(tree[left]);
                }
                left++;
            }

            ans = Math.max(ans, right - left + 1);
        }

        return ans;
    }
}

class Counter extends HashMap<Integer, Integer> {
    public int get(int k) {
        return containsKey(k) ? super.get(k) : 0;
    }

    public void add(int k, int v) {
        put(k, get(k) + v);
    }
}
